package me.green.ui.event;

import me.green.ui.EtnFrame;
import me.green.ui.LocalCache;

import javax.swing.*;
import java.awt.*;
import java.awt.event.AWTEventListener;
import java.awt.event.KeyEvent;

/**
 * 快捷键支持
 * <p>
 * 全局锁住
 *
 * @author Green
 * @version 1.0
 */
public class ShortcutKeyListener implements AWTEventListener {

    private static ShortcutKeyListener listener = null;
    private static Window container = null;

    private boolean pressedCtrl = false;
    private boolean pressedG = false;

    private ShortcutKeyListener() {
    }

    public static ShortcutKeyListener getInstance(Window container) {
        ShortcutKeyListener.container = container;
        if (listener == null) {
            listener = new ShortcutKeyListener();
        }
        return listener;
    }

    @Override
    public void eventDispatched(AWTEvent event) {
        if (event.getClass() == KeyEvent.class) {
            KeyEvent keyEvent = (KeyEvent) event;
            if (keyEvent.getID() == KeyEvent.KEY_PRESSED) {
                keyPressed(keyEvent);
            } else if (keyEvent.getID() == KeyEvent.KEY_RELEASED) {
                keyReleased(keyEvent);
            }
        }
    }

    private void keyPressed(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.VK_ESCAPE && container != null) {
            container.dispose();
        }
        if (event.getKeyCode() == KeyEvent.VK_ALT) {
            pressedCtrl = true;
        }
        if (event.getKeyCode() == KeyEvent.VK_G) {
            pressedG = true;
        }
        if (pressedCtrl && pressedG) {
            if (container instanceof JFrame && ((JFrame) container).getState() == JFrame.NORMAL) {
                // 锁住后最小化
                LocalCache.setLock(true);
                EtnFrame frameApp = LocalCache.getFrameApp();
                frameApp.setState(Frame.ICONIFIED);
            }
        }
    }

    private void keyReleased(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.VK_ALT) {
            pressedCtrl = false;
        }
        if (event.getKeyCode() == KeyEvent.VK_G) {
            pressedG = false;
        }
    }
}
